<template>
  <div class="map-container">
    <!-- 返回按钮 -->
    <div class="back-btn" @click="goBack">
      <el-icon><ArrowLeft /></el-icon>
      <span>返回</span>
    </div>
    
    <!-- 地图容器 -->
    <div id="map" class="map"></div>
    
    <!-- 搜索结果面板 -->
    <div class="search-panel" v-if="searchResults.length">
      <div class="panel-header">
        <span>{{ title }}</span>
        <span>{{ searchResults.length }}个结果</span>
      </div>
      <div class="result-list">
        <div v-for="item in searchResults" 
             :key="item.id"
             class="result-item"
             @click="handleItemClick(item)">
          <div class="item-title">{{ item.name }}</div>
          <div class="item-info">{{ item.address }}</div>
          <div class="item-distance">距离: {{ item.distance }}米</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ArrowLeft } from '@element-plus/icons-vue'

const props = defineProps({
  type: {
    type: String,
    required: true
  },
  title: {
    type: String,
    required: true
  }
})

const router = useRouter()
const map = ref(null)
const searchResults = ref([])

// 初始化地图
const initMap = () => {
  map.value = new TMap.Map('map', {
    center: new TMap.LatLng(39.908802, 116.397502),
    zoom: 12
  })
}

// 加载数据
const loadData = async () => {
  try {
    if (props.type === 'bus') {
      await loadBusStations()
    } else if (props.type === 'school') {
      await loadSchools()
    }
    await loadHouses() // 始终加载房源标记
  } catch (error) {
    console.error('加载数据失败:', error)
  }
}

// 加载公交站点
const loadBusStations = async () => {
  const service = new TMap.service.Search({
    key: 'FSEBZ-TNJCT-QHVXM-VTJSO-5YBZ5-OFFFH'
  })
  
  service.search({
    keyword: '公交站',
    boundary: 'nearby(39.908802,116.397502,2000)', // 搜索2km范围内
    pageSize: 20,
    orderby: '_distance'
  }).then(result => {
    searchResults.value = result.data
    addMarkers(result.data, 'bus')
  })
}

// 加载学校
const loadSchools = async () => {
  const service = new TMap.service.Search({
    key: 'FSEBZ-TNJCT-QHVXM-VTJSO-5YBZ5-OFFFH'
  })
  
  service.search({
    keyword: '学校',
    boundary: 'nearby(39.908802,116.397502,2000)',
    pageSize: 20,
    orderby: '_distance'
  }).then(result => {
    searchResults.value = result.data
    addMarkers(result.data, 'school')
  })
}

// 加载房源标记
const loadHouses = async () => {
  try {
    const response = await fetch('http://127.0.0.1:8000/api/houses/')
    const houses = await response.json()
    addMarkers(houses, 'house')
  } catch (error) {
    console.error('加载房源失败:', error)
  }
}

// 添加标记点
const addMarkers = (items, type) => {
  const markers = new TMap.MultiMarker({
    map: map.value,
    styles: {
      [type]: new TMap.MarkerStyle({
        width: 25,
        height: 25,
        anchor: { x: 12.5, y: 12.5 },
        src: `/markers/${type}.png`
      })
    },
    geometries: items.map(item => ({
      id: item.id,
      styleId: type,
      position: new TMap.LatLng(item.latitude, item.longitude)
    }))
  })

  // 添加点击事件
  markers.on('click', (evt) => {
    const item = items.find(i => i.id === evt.geometry.id)
    handleItemClick(item)
  })
}

// 处理列表项点击
const handleItemClick = (item) => {
  // 将地图中心移动到选中位置
  map.value.setCenter(new TMap.LatLng(item.latitude, item.longitude))
  map.value.setZoom(15)
  
  // 如果是房源则跳转到详情页
  if (item.type === 'house') {
    router.push(`/house/${item.id}`)
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

onMounted(() => {
  initMap()
  loadData()
})
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 100vh;
  position: relative;
}

.map {
  width: 100%;
  height: 100%;
}

.back-btn {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 1;
  background: white;
  padding: 8px 16px;
  border-radius: 4px;
  box-shadow: 0 2px 6px rgba(0,0,0,0.1);
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-panel {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 300px;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 6px rgba(0,0,0,0.1);
  max-height: calc(100vh - 40px);
  overflow-y: auto;
}

.panel-header {
  padding: 12px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
}

.result-list {
  padding: 8px;
}

.result-item {
  padding: 12px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
}

.result-item:hover {
  background: #f5f7fa;
}

.item-title {
  font-weight: bold;
  margin-bottom: 4px;
}

.item-info {
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
}

.item-distance {
  font-size: 12px;
  color: #999;
}
</style> 